const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors'); //跨域
const mongoose = require('mongoose'); //导入mongoose
const token = require('./utility/token'); //token签名、验签
const serverConf = require('./config/server'); //配置连接文件
mongoose.Promise = global.Promise; //设置es6的promise为默认【不使用koa2自己封装的的promise】
mongoose.set('useFindAndModify', false); //设置useFindAndModify为不报错

var mongodb = 'mongodb://' + serverConf.mongodb.user +
    ':' +
    serverConf.mongodb.password +
    '@' + serverConf.mongodb.host +
    ':' + serverConf.mongodb.port +
    '/' +
    serverConf.mongodb.database +
    '?authMechanism=' +
    serverConf.mongodb.authMechanism +
    '&authSource=' +
    serverConf.mongodb.authSource; //数据库地址

// mongoose连接数据库
mongoose.connect(mongodb, {
    useNewUrlParser: true
});

// 跨域配置
app.use(cors({
    origin: function(ctx) {
        if (ctx.url === '/test') {
            return false;
        }
        return '*';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'OPTIONS', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'Content-Length', 'X-Requested-With', 'Access-Control-Allow-Headers'],
}));

// 验证token是否过期【除了login接口的请求外，其他接口都需要验证token】
app.use(async (ctx, next) => {
    if (ctx.request.url != '/acl/login') {
        let webToken = String(ctx.header.authorization);
        if (webToken) {
            let tokenVerify = await token.verify(webToken); //验签
            if (!tokenVerify) {
                ctx.status = 401;
                ctx.body = '登录已过期,请重新登录';
                return;
            }
        } else {
            ctx.status = 401;
            ctx.body = '登录已过期,请重新登录';
            return;
        }
    }
    await next();
});

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
    extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
const _index = require('./routes/index');
app.use(_index.routes(), _index.allowedMethods()); //去除之前引入的路由并且使用路由分发

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app